//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
//#include <elasys_server.h>
#include <winhack.h>
#include <elapi.h>
#include <stdio.h>
#include "battery.h"
#include <sysconfig.h>
static CBattery battery;

ECode CBattery::Read(
    /* [in] */ Int64 u64Offset,
    /* [in] */ Int32 bytesToRead,
    /* [out] */ MemoryBuf * pBuffer,
    /* [out] */ IEvent * * ppCompletionEvent)
{
    return E_NOT_IMPLEMENTED;
}

ECode CBattery::Write(
    /* [in] */ Int64 u64Offset,
    /* [in] */ const MemoryBuf & buffer,
    /* [out] */ Int32 * pBytesWritten,
    /* [out] */ IEvent * * ppCompletionEvent)
{
    return E_NOT_IMPLEMENTED;
}

ECode CBattery::Control(
    /* [in] */ Handle32 nControlCode,
    /* [in] */ const MemoryBuf & inBuffer,
    /* [out] */ MemoryBuf * pOutBuffer,
    /* [out] */ IEvent * * ppCompletionEvent)
{
    switch (nControlCode) {
        case 0:{//Power Consume

            int consumption = *(int *)inBuffer.GetPayload();//is it NULL?judge first.
            TotalConsumption+=consumption;
            break;
        }
        default :
            break;
    }
    return NOERROR;
}

bool CBattery::Initialize()
{
    Capacity=2400000;//1000*4*60*60
    TotalConsumption=0;
    ECode ec = _CThread_New((PThreadMain)NotifyThread, (PVoid)this, 0, NULL);
    if (FAILED(ec)) {
        return false;
    }
    return true;
}

int CBattery::NotifyThread(PVoid parg)
{
    printf("-----------------------------------starting real time capacity report\n");
    CBattery * pThis=(CBattery *)parg;
    while (true) {
        UInt32 level=100*(pThis->Capacity - pThis->TotalConsumption) / pThis->Capacity;
        _CThread_Sleep(30*1000, NULL);
        printf("--------------------------------real time capacity report:%d\n",level);
    }
    return 0;
}

EXTERN IDeviceDriver * CDECL CreateBattery(uint_t uDeviceNo, void *pvParameter)
{
    int IsPowerManagerNeeded=0;
    ECode ec = ConfigGetItemInt(L"powermanager", &IsPowerManagerNeeded);
    if(FAILED(ec) || !IsPowerManagerNeeded)
		return NULL;
    CBattery * pBattery = &battery;
    if(!(pBattery->Initialize()))
		return NULL;

    return pBattery;
}
